﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using KPIS.GERP.GIMS.DAL;
using KPIS.GERP.GIMS.MODEL;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;


namespace KPIS.GERP.GIMS.APP.APP_UI.Add_Form
{
    public partial class ICM_Number_Cut_Stock : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        D_StockMovement d_stock_movement = new D_StockMovement();
        M_StockMovement m_stock_movement = new M_StockMovement();
        D_Requisition_Desc d_requisition_desc = new D_Requisition_Desc();
        M_Requisition_Desc m_requisition_desc = new M_Requisition_Desc();
        D_TempCutStock d_temp_cut_stock = new D_TempCutStock();
        M_TempCutStock m_temp_cut_stock = new M_TempCutStock();
        D_IcmReceiveObject d_receive = new D_IcmReceiveObject();
        M_IcmReceiveObject m_receive = new M_IcmReceiveObject();
        D_Requisition d_requisition = new D_Requisition();
        M_Requisition m_requisition = new M_Requisition();
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UpdateUI1("Load");
                hrequisiton_des_item.Text = Request.QueryString["requisiton_des_item"].ToString();
                M_Requisition_Desc info = d_requisition_desc.GetListFillBySeq(cn.ConvertNullInt(hrequisiton_des_item.Text));
                txtRequestQuantity.Text = info.quantity.ToString();
                pInventory.Text = info.icm_res_item_name.ToString();
                hJobSiteSeq.Text = Request.QueryString["JobSiteSeq"].ToString();
                hicm_res_item_seq.Text = Request.QueryString["icm_res_item_seq"].ToString();
                txtRealQuantity.Text = Request.QueryString["cutstock_real_quantity"].ToString();
                hrequisition_code.Text = Request.QueryString["requisition_code"].ToString();
                txtRealQuantity.Focus();
                LoadGrid();
                grdInventoryFIFO.DataBind();
                if (d_stock_movement.CheckEditValue(cn.ConvertNullInt(hrequisiton_des_item.Text), cn.ConvertNullInt(hicm_res_item_seq.Text)) == 0)
                {
                    try
                    {
                        hmovementcode.Text = fncGenerate_MovementCode();
                        m_stock_movement.movement_code = hmovementcode.Text;
                        m_stock_movement.requisiton_des_item = Convert.ToInt32(hrequisiton_des_item.Text);
                        m_stock_movement.to_job_site_seq = Convert.ToInt32(hJobSiteSeq.Text);
                        m_stock_movement.icm_res_item_seq = Convert.ToInt32(hicm_res_item_seq.Text);
                        m_stock_movement.request_quantity = Convert.ToDouble(txtRequestQuantity.Text);
                        m_stock_movement.cutstock_real_quantity = Convert.ToDouble(txtRequestQuantity.Text);
                        m_stock_movement.created_by = cn.UserID;
                        m_stock_movement.created_when = DateTime.Now;
                        d_stock_movement.Insert_StockMovement(m_stock_movement);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                }
                else
                {
                    hmovementcode.Text = Request.QueryString["movement_code"].ToString();
                }
            }
        }
        protected void btnCompare_Click(object sender, EventArgs e)
        {
                  Int32 row = grdInventoryFIFO.Items.Count;
                  hRealQuantity.Text = txtRealQuantity.Text;
                  d_temp_cut_stock.Delete_TempCutStock();
                  DataTable dt = new DataTable();
                  dt = d_stock_movement.GetListDataTableFIFOInventoryReceive(cn.ConvertNullInt(hicm_res_item_seq.Text));


                  if (dt.Rows.Count > 0)
                  {
                      hreceive_seq.Text = dt.Rows[0]["icm_receive_seq"].ToString();//data.OwnerTableView.DataKeyValues[data.ItemIndex]["icm_receive_seq"].ToString();
                      M_IcmReceiveObject info = d_stock_movement.GetListFIFOFillBySeq(cn.ConvertNullInt(hicm_res_item_seq.Text), cn.ConvertNullInt(hreceive_seq.Text));

                      if (info.quantity_remain_after >= Convert.ToDouble(txtRealQuantity.Text))
                      {
                          m_receive.icm_receive_seq = Convert.ToInt32(hreceive_seq.Text);
                          m_receive.quantity_remain_after = Convert.ToDouble(info.quantity_remain_after) - Convert.ToDouble(txtRealQuantity.Text);
                          m_receive.cut_stock_by = cn.UserID;
                          m_receive.cut_stock_when = DateTime.Now;
                          d_receive.Update_Cut_Stock_FIFO_Preview(m_receive);

                          m_temp_cut_stock.icm_receive_seq = m_receive.icm_receive_seq;
                          m_temp_cut_stock.quantity = info.quantity_remain_before;
                          m_temp_cut_stock.quantity_cut_stock = Convert.ToDouble(txtRealQuantity.Text);
                          d_temp_cut_stock.Insert_TempCutStock(m_temp_cut_stock);
                          // break;
                      }
                      else if (info.quantity_remain_after < Convert.ToDouble(txtRealQuantity.Text))
                      {
                          double dCheckQuantity = d_stock_movement.CheckQuantityCutStock(cn.ConvertNullInt(hicm_res_item_seq.Text));
                          hCountLineCutstock.Text = "0";
                          if (dCheckQuantity > Convert.ToDouble(txtRealQuantity.Text))
                          {
                              hRealQuantity.Text = txtRealQuantity.Text;
                              foreach (DataRow dr in dt.Rows)
                              {
                                  if (Convert.ToDouble(hRealQuantity.Text) >= Convert.ToDouble(dr["quantity_remain_before"].ToString()))
                                  {
                                      hCountLineCutstock.Text = Convert.ToString(Convert.ToInt32(hCountLineCutstock.Text) + 1);
                                      hRealQuantity.Text = Convert.ToString(Convert.ToDouble(hRealQuantity.Text) - Convert.ToDouble(dr["quantity_remain_before"].ToString()));

                                      //Test Cutstock
                                      m_receive.icm_receive_seq = Convert.ToInt32(dr["icm_receive_seq"].ToString());
                                      m_receive.quantity_remain_after = 0;
                                      m_receive.cut_stock_by = cn.UserID;
                                      m_receive.cut_stock_when = DateTime.Now;
                                      d_receive.Update_Cut_Stock_FIFO_Preview(m_receive);

                                      //Keep Temp เพื่อใช้สำหรับการ Save
                                      m_temp_cut_stock.icm_receive_seq = Convert.ToInt32(dr["icm_receive_seq"].ToString());
                                      m_temp_cut_stock.quantity = Convert.ToDouble(txtRealQuantity.Text);
                                      m_temp_cut_stock.quantity_cut_stock = Convert.ToDouble(dr["quantity_remain_after"].ToString());
                                      d_temp_cut_stock.Insert_TempCutStock(m_temp_cut_stock);
                                  }
                                  else if (Convert.ToDouble(hRealQuantity.Text) > 0)
                                  {
                                      //Test Cutstock
                                      m_receive.icm_receive_seq = Convert.ToInt32(dr["icm_receive_seq"].ToString());
                                      m_receive.quantity_remain_after = Convert.ToDouble(dr["quantity_remain_after"].ToString()) - Convert.ToDouble(hRealQuantity.Text);
                                      m_receive.cut_stock_by = cn.UserID;
                                      m_receive.cut_stock_when = DateTime.Now;
                                      d_receive.Update_Cut_Stock_FIFO_Preview(m_receive);

                                      //Keep Temp เพื่อใช้สำหรับการ Save
                                      m_temp_cut_stock.icm_receive_seq = Convert.ToInt32(dr["icm_receive_seq"].ToString());
                                      m_temp_cut_stock.quantity = Convert.ToDouble(txtRealQuantity.Text);
                                      m_temp_cut_stock.quantity_cut_stock = Convert.ToDouble(hRealQuantity.Text);
                                      d_temp_cut_stock.Insert_TempCutStock(m_temp_cut_stock);
                                      hRealQuantity.Text = "0";
                                  }
                                  else
                                  {
                                      break;
                                  }
                              }
                          }
                          else
                          {
                              RadAjaxManager1.Alert("จำนวนพัสดุที่มีอยู่ในคลังไม่พอให้เบิก");
                          }
                      }
                      LoadGrid();
                      grdInventoryFIFO.DataBind();
                      UpdateUI1("Compare");
                  }
                  else
                  {
                      RadAjaxManager1.Alert("ไม่มีการรับของพัสดุชิ้นนี้ในคลัง");
                  }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            UpdateUI1("Cancel");
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckValidate())
            {
                DataTable dt = new DataTable();
                DataTable dtReceive = new DataTable();
                Int32 i = 0;
                dt = d_temp_cut_stock.GetDataTableTemp();
                try
                {
                    UpdateUI1("Save");
                    //if (txtRealQuantity.Text != txtRequestQuantity.Text)
                    //{
                    //    m_stock_movement.movement_code = hmovementcode.Text;
                    //    m_stock_movement.cutstock_real_quantity = Convert.ToDouble(txtRealQuantity.Text);
                    //    m_stock_movement.created_by = cn.UserID;
                    //    m_stock_movement.created_when = DateTime.Now;
                    //    m_stock_movement.icm_receive_seq = 55;
                    //    d_stock_movement.Update_StockMovement(m_stock_movement);
                    //}
                    foreach (DataRow dr in dt.Rows)
                    {
                        hreceive_seq.Text = dr["icm_receive_seq"].ToString();
                        M_IcmReceiveObject infoReceive = d_stock_movement.GetListFIFOIncreaseZeroFillBySeq(cn.ConvertNullInt(hicm_res_item_seq.Text), cn.ConvertNullInt(hreceive_seq.Text));
                        m_receive.icm_receive_seq = Convert.ToInt32(hreceive_seq.Text);
                        m_receive.cut_stock_by = cn.UserID;
                        m_receive.cut_stock_when = DateTime.Now;
                        m_receive.quantity_remain = Convert.ToDouble(infoReceive.quantity_remain_before) - Convert.ToDouble(dt.Rows[i]["quantity_cut_stock"]);
                        m_receive.quantity_remain_before = m_receive.quantity_remain;
                        d_receive.Update_Cut_Stock_FIFO(m_receive);
                        if (dt.Rows.Count == 1)
                        {
                            m_stock_movement.movement_code = hmovementcode.Text;
                            m_stock_movement.cutstock_real_quantity = Convert.ToDouble(txtRealQuantity.Text);
                            m_stock_movement.created_by = cn.UserID;
                            m_stock_movement.created_when = DateTime.Now;
                            m_stock_movement.icm_receive_seq = cn.ConvertNullInt(hreceive_seq.Text);
                            d_stock_movement.Update_StockMovement(m_stock_movement);
                        }
                        else if (dt.Rows.Count > 1 )
                        {
                            m_stock_movement.movement_code = hmovementcode.Text;
                            m_stock_movement.icm_receive_seq = cn.ConvertNullInt(hreceive_seq.Text);
                            m_stock_movement.to_job_site_seq = Convert.ToInt32(hJobSiteSeq.Text);
                            m_stock_movement.icm_res_item_seq = Convert.ToInt32(hicm_res_item_seq.Text);
                            m_stock_movement.requisiton_des_item = Convert.ToInt32(hrequisiton_des_item.Text);
                            m_stock_movement.request_quantity = Convert.ToDouble(dt.Rows[i]["quantity"].ToString());
                            m_stock_movement.cutstock_real_quantity = Convert.ToDouble(dt.Rows[i]["quantity_cut_stock"].ToString());// m_receive.quantity_remain_before;
                            m_stock_movement.created_by = cn.UserID;
                            m_stock_movement.created_when = DateTime.Now;
                            d_stock_movement.Insert_StockMovement(m_stock_movement);
                        }
                    }
                    i = +1;
                    m_requisition.requisition_code = hrequisition_code.Text;
                    m_requisition.cutstock_by = cn.UserID;
                    m_requisition.cutstock_when = DateTime.Now;
                    m_requisition.movement_code = hmovementcode.Text;
                    d_requisition.CutStock_Requisition(m_requisition);

                }
                catch (Exception ex)
                {
                    throw (ex);
                }
                finally
                {
                    d_temp_cut_stock.Delete_TempCutStock();
                    RadAjaxManager1.ResponseScripts.Add(@"CloseWindow();");
                }
            }
        }
        protected void grdInventoryFIFO_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            LoadGrid();
        }
        private void LoadGrid()
        {
            grdInventoryFIFO.DataSource = d_stock_movement.GetListFIFOInventoryReceive(cn.ConvertNullInt(hicm_res_item_seq.Text));
        }
        private bool CheckValidate()
        {
            bool pFlag = true;
            if (txtRealQuantity.Text == "")
            {
                pFlag = false;
                txtRealQuantity.Focus();
                RadAjaxManager1.Alert("กรุณากรอกจำนวนที่ยอมให้เบิกจริงด้วย");
            }
            return pFlag;
        }
        private void UpdateUI1(string strCommand)
        {
            switch (strCommand)
            {
                case "Load":
                    btnCompare.Enabled = true;
                   // btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    break;
                case "Compare":
                    btnCompare.Enabled = false;
                  //  btnCancel.Enabled = true;
                    btnSave.Enabled = true;
                    break;
                case "Save":
                    btnCompare.Enabled = true;
                  //  btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    break;
                case "Cancel":
                    btnCompare.Enabled = true;
                   // btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    break;
            }
        }
        private string fncGenerate_MovementCode()
        {
            string strMonth = "";
            string strYear = "";
            string strRunning = "";
            string strRequisition = "";
            try
            {
                M_StockMovement infoMovement = d_stock_movement.GenerateMovementCode();
                strYear = infoMovement.str_year;
                strMonth = cn.ConvertstrMonth(infoMovement.str_month);
                strRunning = cn.ConvertstrRunningFiveDigit(infoMovement.movement_running);
                strRequisition = "MM" + strYear + "-" + strMonth + "-" + strRunning;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return strRequisition;
        }
    }
}
